<?php


namespace App\Http\Controllers\Admin;
use App\Lib\UploadLib;
use App\Models\Banner;
use Illuminate\Http\Request;

class BannerController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $users = Banner::orderBy('sort', 'desc')->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    /**
     * 详情
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:banner'
        ]);
        $id = \request("id");
        $info = Banner::find($id);
        return $this->success($info);
    }

    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'logo' => 'required',
//            'url' => array('regex:/(https?|http?|ftp?):\/\/?/i'),
            'sort' => 'filled|integer',
//            'type' => 'required|in:1,2,3',
            'id' => 'filled|exists:banner'
        ]);
        $input = $request->input();
        $id = \request("id");
        if ($id) {
            if ($request->hasFile('logo')) {
                $input['logo'] = UploadLib::handle($request->file('logo'));
            }
            Banner::where('id', $id)->update($input);
        } else {
            if (!$request->hasFile('logo')) {
                return $this->failed("logo类型有误");
            }
            $input['logo'] = UploadLib::handle($request->file('logo'));
            $info = Banner::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:banner'
        ]);
        $id = $request->input('id');
        Banner::where('id', $id)->delete();
        return $this->success([]);
    }


}

